package com.example.service;



import com.example.DTO.LogInDTO;
import com.example.DTO.Register;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    // 注册
    @Override
    public User register(Register registerDTO) {
        // 1. 检查两次密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            throw new RuntimeException("两次密码输入不一致");
        }

        // 2. 检查手机号是否已存在
        if (checkPhoneExists(registerDTO.getPhone())) {
            throw new RuntimeException("手机号已被注册");
        }

        // 3. 检查昵称是否已存在
        if (checkNicknameExists(registerDTO.getNickname())) {
            throw new RuntimeException("昵称已被使用");
        }

        // 4. 创建用户对象
        User user = new User();
        user.setNickname(registerDTO.getNickname());
        user.setPhone(registerDTO.getPhone());

        // 5. 对密码进行MD5加密（简单加密）
        String encryptedPassword = DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes());
        user.setPassword(encryptedPassword);

        // 6. 插入数据库
        userMapper.insertUser(user);

        return user;
    }

    /**
     *
     * 登录逻辑
     *
     */
    @Override
    public User login(LogInDTO loginDTO) {
        System.out.println("登录请求: " + loginDTO.getUsername());

        // 1. 先尝试用手机号查找用户
        User user = userMapper.findByPhone(loginDTO.getUsername());

        // 2. 如果没找到，再用昵称查找
        if (user == null) {
            user = userMapper.findByNickname(loginDTO.getUsername());
        }

        // 3. 如果用户不存在
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 4. 验证密码
        String inputPassword = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if (!inputPassword.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        System.out.println("登录成功: " + user.getNickname());
        return user;
    }
    @Override
    public boolean checkPhoneExists(String phone) {
        return userMapper.countByPhone(phone) > 0;
    }
    @Override
    public boolean checkNicknameExists(String nickname) {
        return userMapper.countByNickname(nickname) > 0;
    }
}